package com.loong.game2048.controller;

import com.loong.game2048.Exception.BizException;
import com.loong.game2048.annotation.Authorize;
import com.loong.game2048.module.ResultCode;
import com.loong.game2048.module.User;
import com.loong.game2048.module.vo.Result;
import com.loong.game2048.module.vo.WXCodeVo;
import com.loong.game2048.module.vo.WXSession;
import com.loong.game2048.server.UserServer;
import com.loong.game2048.util.HttpClientUtils;
import com.loong.game2048.util.JsonUtils;
import com.loong.game2048.util.RedisUtils;
import com.loong.game2048.util.ResultUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lyx
 * @date 2020/5/9 10:32
 */
@RestController
public class UserController {



    @Resource
    private RedisUtils redisUtils;

    @Resource
    private UserServer userServer;

    /**
     * 小程序微信登录
     * @param code
     * @return
     */
    @PostMapping("/wxLogin")
    public Result WXLogin(@RequestBody WXCodeVo code){
        Result result = new Result();
//        GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String,String> param = new HashMap<>();
        param.put("appid","wx5d621b43eb4fc0ed");
        param.put("secret","5022a731378386a61ef2ae6676cae829");
        param.put("js_code",code.getCode());
        param.put("grant_type","authorization_code");
        //最终获得一个json字符串
        String  wxResult = HttpClientUtils.doGet(url,param);
        WXSession wxSession = JsonUtils.jsonToPojo(wxResult, WXSession.class);
        if (wxSession == null){
            result.setCode(ResultCode.UNSPECIFIED);
            result.setMsg("登录失败");
        }else{
            //存入redis缓存
            redisUtils.set("user-session:"+wxSession.getOpenid(),wxSession.getSession_key(),64800);
            result.setToken("user-session:"+wxSession.getOpenid());
            if (userServer.getUserCountById(wxSession.getOpenid())>0){
                result.setCode(1);
                result.setMsg("登录成功");
                result.setData(userServer.getUserById(wxSession.getOpenid()));
            }else{
                //此用户第一次登录，插入信息到数据库中
                userServer.addUser(wxSession.getOpenid());
                result.setCode(0);
                result.setMsg("登录成功，但此用户还未保存用户信息到数据库，请调用另一接口保存用户信息");

            }
        }
        return result;
    }


    /**
     * 修改用户昵称，头像信息
     * @param user
     * @param request
     * @return
     */
    @Authorize //注解，判断用户是否登录
    @PostMapping("/updateUserMsg")
    public Result updateUserMsg(@RequestBody User user, HttpServletRequest request){
        Result result = new Result();
        if (user!=null){
            user.setOpenId(ResultUtils.getOpenId(request));
            if (userServer.updateUserMsg(user)>0){
                result.setCode(ResultCode.SUCCESS);
                result.setMsg("修改客户信息成功");
                result.setData(user);
            }else{
                result.setCode(ResultCode.UNSPECIFIED);
                result.setMsg("修改客户信息失败");
            }
        }else{
            result.setCode(ResultCode.PARAMETER_ERROR);
            result.setMsg("传参为空");
        }
        return result;
    }

    /**
     * 修改用户背景图片
     * @param
     * @return
     */
    @Authorize
    @GetMapping("/updateBackGround")
    public Result updateBackGround(@RequestParam("background")String background,HttpServletRequest request){
        User user = new User();
        user.setOpenId(ResultUtils.getOpenId(request));
        user.setBackground(background);
        userServer.updateUserBackground(user);
        return new Result(userServer.getUserById(user.getOpenId()));
    }

    @Authorize
    @GetMapping("/getUserMsg")
    public Result getUserMsg(HttpServletRequest request){
        String openId = ResultUtils.getOpenId(request);
        return new Result(userServer.getUserById(openId));
    }
    

    /**
     * 测试登录
     * @param wxSession
     * @return
     */
    @PostMapping("/testLogin")
    public Result testLogin(@RequestBody WXSession wxSession){
        Result result = new Result();
        if (wxSession == null){
            result.setCode(ResultCode.UNSPECIFIED);
            result.setMsg("登录失败");
        }else{
            //存入redis缓存
            redisUtils.set("user-session:"+wxSession.getOpenid(),wxSession.getSession_key()+"",64800);
            result.setToken("user-session:"+wxSession.getOpenid());
            if (userServer.getUserCountById(wxSession.getOpenid())>0){
                result.setCode(1);
                result.setMsg("登录成功");
                result.setData(userServer.getUserById(wxSession.getOpenid()));
            }else{
                //此用户第一次登录，插入信息到数据库中
                if (userServer.addUser(wxSession.getOpenid())>0){
                    result.setCode(0);
                    result.setMsg("登录成功，但此用户还未保存用户信息到数据库，请调用另一接口保存用户信息");
                }else {
                    result.setCode(ResultCode.UNSPECIFIED);
                    result.setMsg("登录失败");
                }
            }
        }
        return result;
    }

}
